<?php
include_once(DB_FILE);

class Alarm
{
    /** Costrutture della classe
    * @param void.
    */
    var $NUM_RECORDS=37;
    var $ARR_SOGLIE=array();
    var $ARR_PRE_SOGLIE=array();

    
    var $SMS="sms";
    var $FAX="fax";
    var $EMAIL="email";

    function Alarm()
    {
        $this->getSogliePresoglie();
    }
    
    private function getSogliePresoglie()
    {
         $msql  = new Db;
         $msql->connect();
         
         $arr=$msql->execute_select("SELECT * FROM valori_soglie_presoglie");
         
         for ($row = 0; $row < count($arr); $row++)
            {
               $this->ARR_SOGLIE[$row]=$arr[$row][1];
               $this->ARR_PRE_SOGLIE[$row]=$arr[$row][2];
            }
        
        //print_r($this->ARR_SOGLIE);
        //print_r($this->ARR_PRE_SOGLIE);
        $msql->disconnettiDB();
        
         
    }
    
    function checkStatusSistema()
    {
         $msql  = new Db;
         $msql->connect();
    }

    /** checkTrasmission1o2o0
    * Questo messaggio inviato se una o piu' centraline
    * stanno trasmettendo su codice di trasmissione 1 o 2 o 0.
    */
    function checkTrasmission1o2o0()
    {
	$log=new FileLog();
	$log->writeLog( __FUNCTION__ );
	$log->close();
	
        $msql  = new Db;
        $msql->connect();
        
        //$query="SELECT data,P1Rx,P2Rx,P3Rx,P4Rx,P5Rx,P6Rx,P7Rx,P8Rx,P9Rx,P10Rx,P11Rx,P12Rx,P13Rx,P14Rx,P15Rx from dati_impianto where P1Rx = $value || P2Rx = $value || P3Rx = $value || P4Rx = $value || P5Rx = $value || P6Rx = $value || P7Rx = $value || P8Rx = $value || P9Rx = $value || P10Rx = $value || P11Rx = $value || P12Rx = $value || P13Rx = $value || P14Rx = $value || P15Rx = $value;";
        //$query="SELECT data,P1Rx,P2Rx,P3Rx,P4Rx,P5Rx,P6Rx,P7Rx,P8Rx,P9Rx,P10Rx,P11Rx,P12Rx,P13Rx,P14Rx,P15Rx,id from dati_impianto where  id Not in (select id_dati_impianto from alarm_3) && (P1Rx = 1 || P2Rx = 1 || P3Rx = 1 || P4Rx = 1 || P5Rx = 1 || P6Rx = 1 || P7Rx = 1 || P8Rx = 1 || P9Rx = 1 || P10Rx = 1 || P11Rx = 1 || P12Rx = 1 || P13Rx = 1 || P14Rx = 1 || P15Rx = 1) and P1Rx Not in (select Rx from alarm_3);";
        $query="SELECT data,P1Rx,P2Rx,P3Rx,P4Rx,P5Rx,P6Rx,P7Rx,P8Rx,P9Rx,P10Rx,P11Rx,P12Rx,P13Rx,P14Rx,P15Rx,id from dati_impianto order by data desc limit 4;";
        $query_alarm="INSERT INTO alarm_trasmissione (Rx,data,id_dati_impianto,val_trasmissione,val_trasmissione_old,alarm_id) VALUES ";
        $arr=$msql->execute_select($query);
        echo $query;
        //print_r($arr);
        for ($row = 0; $row < count($arr)-1; $row++)
        {
            for ($col=1;$col< count($arr[$row])-1; $col++)
            {
                    if($arr[$row][$col] != $arr[$row+1][$col])
                    {
                        $data=$arr[$row][0]; //data query
                        $id=$arr[$row][16]; //id query
                        $arr_alarm=$msql->execute_select("SELECT * from alarm_trasmissione where id_dati_impianto=$id && Rx=$col;");
                        if(count($arr_alarm)==0)
                        {
                            $id_alarm=2; //funzionamento parziale della trasmissione 1 o 2
                            if( $arr[$row][$col]== 3 && $arr[$row+1][$col]== 0 )
                                $id_alarm=10;
                            
                            else if ($arr[$row][$col]== 0 && $arr[$row+1][$col]== 3)
                                $id_alarm=3;
                            else if ($arr[$row][$col]== 0 && $arr[$row+1][$col]== 1)
                                $id_alarm=3;
                            else if ($arr[$row][$col]== 0 && $arr[$row+1][$col]== 2)
                                $id_alarm=3;

                            else if ($arr[$row][$col]== 1 && $arr[$row+1][$col]== 0)
                                $id_alarm=2;
                            else if ($arr[$row][$col]== 2 && $arr[$row+1][$col]== 0) // non funziona la trasmissione 0
                                $id_alarm=2;
                            
                            else if ($arr[$row][$col]== 3 && ($arr[$row+1][$col]== 1 || ($arr[$row+1][$col]== 2 )))
                                 $id_alarm=9;

                            echo $query_alarm."($col,\"$data\",$id,".$arr[$row][$col].",".$arr[$row+1][$col].");";
                            $msql->execute($query_alarm."($col,\"$data\",$id,".$arr[$row][$col].",".$arr[$row+1][$col].",".$id_alarm.");");
                        }
                    }
            }
        }
        $msql->disconnettiDB();
        return 0;
    }
    
    function sogliaAllarme()
    {
	$log=new FileLog();
	$log->writeLog( __FUNCTION__ );
	$log->close();
	
        $msql  = new Db;
        $msql->connect();
	
	$pre_arr_soglie=$this->ARR_PRE_SOGLIE;
        $arr_soglie=$this->ARR_SOGLIE;

        $query="SELECT data,id,P1Pz01, P2Pz02,  P2Pz03,  P3Pz04,  P3Pz05,  P4Pz06,  P4Pz07,  P4Pz08,  P5Pz09,  P5Pz10,  P6Pz11,  P6Pz12,  P6Pz13,  P7Pz14,  P7Pz15,  P7Pz16,  P8Pz17,  P8Pz18,  P8Pz19,  P9Pz20,  P9Pz21,  P9Pz22,  P10Pz23,  P10Pz24,  P10Pz25,  P11Pz26,  P11Pz27,  P11Pz28,  P12Pz29,  P12Pz30,  P13Pz31,  P13Pz32,  P13Pz33,  P14Pz34,  P14Pz35,  P14Pz36,  P15Pz37 from dati_impianto order by data desc limit 4";
        $query_alarm="INSERT INTO alarm_soglia (Rx,alarm_displayed,data,valore,alarm_id,id_dati_impianto) VALUES ";
        $arr=$msql->execute_select($query);
        $num_campi=2;//count($arr)-1
        for ($row = 0; $row < count($arr); $row++)
        {
            for ($col=$num_campi;$col< count($arr[$row])-1; $col++)
            {
                    $data=$arr[$row][0];
                    $id=$arr[$row][1];
                    
                    if( ($arr[$row][$col] > $arr_soglie[$col-$num_campi]) && ($arr[$row][$col] != -9999) ) //superamento soglia
                    {
                        //controlla se non e' stato gia alzato lo stesso allarme
                        $arr_tmp=$msql->execute_select("SELECT * from alarm_soglia where id_dati_impianto=$id");
                        if(count($arr_tmp)==0)
                        {
                            echo "$id Soglia di Allarme superata nei piezometri sezione ".($col-1)." soglia ".$arr_soglie[$col-$num_campi]." valore ".$arr[$row][$col]."\n";
                            $msql->execute($query_alarm."(".($col-1).",true,\"$data\",".$arr[$row][$col].",5,$id);");
                        }
                   }
                   else if( ($arr[$row][$col] > $pre_arr_soglie[$col-$num_campi]) && ($arr[$row][$col] != -9999) ) // superamento presoglia
                    {
                        $arr_tmp=$msql->execute_select("SELECT * from alarm_soglia where id_dati_impianto=$id");
                        if(count($arr_tmp)==0)
                        {
                            echo "$id Soglia di Preallarme superata nei piezometri sezione ".($col-1)." soglia ".$pre_arr_soglie[$col-$num_campi]." valore ".$arr[$row][$col]."\n";
                            $msql->execute_select($query_alarm."(".($col-1).",true,\"$data\",".$arr[$row][$col].",4,$id);");
                        }
                    }
                    else if(($arr[$row][$col] < $arr_soglie[$col-$num_campi]) && ($arr[$row][$col] > $pre_arr_soglie[$col-$num_campi]) && ($arr[$row][$col] != -9999) )//   preSogila < valore < Soglia
                    {
                        //controlla se l'allarme e' stato alzato precedentemente
                        $arr_tmp_true=$msql->execute_select("SELECT count(id) from alarm_soglia where alarm_id = 5 && alarm_displayed=true && Rx=".($col-1));
                        $arr_tmp_false=$msql->execute_select("SELECT count(id) from alarm_soglia where alarm_id = 12 && alarm_displayed=false && Rx=".($col-1));
                        if($arr_tmp_true[0][0] != $arr_tmp_false[0][0]) //il numero di allrmi a video per il segnale i true e false non sono uguali
                        {
                            echo $arr[$row][1]." Allarme sezione ".($col-1)." rientrato nei piezometri sezione ".($col-1)." valore ".$arr_soglie[$col-$num_campi]."\n";
                            $msql->execute($query_alarm."(".($col-1).",false,\"$data\",".$arr[$row][$col].",12,$id);");
                        }
                    }
                    else if(($arr[$row][$col] < $pre_arr_soglie[$col-$num_campi]) && ($arr[$row][$col] != -9999) ) //valore < presoglia
                    {
                        //controlla se l'allarme e' stato alzato precedentemente
                        $arr_tmp_true=$msql->execute_select("SELECT count(id) from alarm_soglia where alarm_id = 4 && alarm_displayed=true && Rx=".($col-1));
                        $arr_tmp_false=$msql->execute_select("SELECT count(id) from alarm_soglia where alarm_id = 11 && alarm_displayed=false && Rx=".($col-1));
                        if($arr_tmp_true[0][0] != $arr_tmp_false[0][0]) //il numero di allrmi a video per il segnale i true e false non sono uguali
                        {
                            $msql->execute($query_alarm."(".($col-1).",false,\"$data\",".$arr[$row][$col].",11,$id);");
                            echo $arr[$row][1]." Preallarme sezione ".($col-1)." rientrato\n";
                        }
                    }
                    
            }
        }
        $msql->disconnettiDB();
        return 0;
    }
    
    function sogliaAllarmPre()
    {
        global $DATA_SCHEDULE;

	$log=new FileLog();
	$log->writeLog(__FUNCTION__ );
	$log->close();
	
        $msql  = new Db;
        $msql->connect();
      
        $data=strtotime( $DATA_SCHEDULE );
	$data_sec=$data- 3600;
	$data_less_hour=strftime('%Y-%m-%d %H:%M:%S',$data_sec);
        
	$query_alarm="INSERT INTO alarm_preallarme_previsione (Rx,alarm_displayed,offset,data_previsione,alarm_id,data) VALUES ";
	$val=$this->NUM_RECORDS;
	for ($i=1;$i<=$this->NUM_RECORDS;$i++) //Num record eliminando il segnale
        {
           
            $segnale_str="P".$i."Pz";
            $segnale=$i;
            $value_soglia=$this->ARR_SOGLIE[$i-1];
            $value_pre_soglia=$this->ARR_PRE_SOGLIE[$i-1];

            $query_soglia="SELECT ora_pre, id,$segnale_str FROM simulazioni where $segnale_str >= $value_soglia && $segnale_str <> -9999 && data_insert = '".$DATA_SCHEDULE."' && ora_pre > 0 order by ora_pre limit 1";
            $query_pre_soglia="SELECT ora_pre, id,$segnale_str FROM simulazioni where $segnale_str < $value_soglia && $segnale_str <> -9999 && $segnale_str >= $value_pre_soglia  && data_insert = '".$DATA_SCHEDULE."' && ora_pre > 0 order by ora_pre limit 1";


            $arr_soglia=$msql->execute_select($query_soglia);
            $n_soglia=count($arr_soglia);
            $arr_pre_soglia=$msql->execute_select($query_pre_soglia);
            $n_pre_soglia=count($arr_pre_soglia);

            //Segnaliamo prima l'allarme di soglia e se non vi sono
            //allarmi di soglia si passa a valutare quelli di presoglia
            if($n_soglia>0)
            {
                $arr=&$arr_soglia;
                $alarm_id=7;
            }
            else if($n_pre_soglia>0)
            {
                $alarm_id=6;
                $arr=&$arr_pre_soglia;
            }

            if($n_soglia > 0 || $n_pre_soglia > 0) //il primo valore superiore alla soglia in previsione
            {
                
                $offset=$arr[0][0];
                $id=$arr[0][1];
                $Pz=$arr[0][2];
                $insert=false;
                echo "SELECT Rx, alarm_displayed,offset FROM alarm_preallarme_previsione where Rx=$segnale && alarm_displayed=true && alarm_id=$alarm_id";
                $alarm_arr=$msql->execute_select("SELECT Rx, alarm_displayed,offset FROM alarm_preallarme_previsione where Rx=$segnale && alarm_displayed=true && alarm_id=$alarm_id");
                if(count($alarm_arr) > 0)
                {
                    print_r($alarm_arr);
                    $offset_alarm=$alarm_arr[0][2];
                    if( ($offset_alarm-$offset) > 1 ) //se non ancora segnalato va segnalato
                    {
                        $insert=true;
                    }
                }
                else
                    $insert=true; //mai segnalato va segnalato

                if($insert)
                {
                    $data=strtotime( $DATA_SCHEDULE );
                    $data_sec=$data+ 3600*$offset;
                    $data_less_hour=strftime('%Y-%m-%d %H:%M:%S',$data_sec);

                    $msql->execute($query_alarm." ($segnale,true,$offset,'$data_less_hour',$alarm_id,'$DATA_SCHEDULE');");
                }
            }
            else
            {
		
                echo "\nSELECT Rx, alarm_displayed,offset FROM alarm_preallarme_previsione where Rx=$segnale && alarm_displayed=true and Rx not in (SELECT Rx FROM alarm_preallarme_previsione where Rx=$segnale && alarm_displayed=false);";

                $alarm_arr=$msql->execute_select("SELECT Rx, alarm_displayed,offset,alarm_id FROM alarm_preallarme_previsione where Rx=$segnale && alarm_displayed=true and Rx not in (SELECT Rx FROM alarm_preallarme_previsione where Rx=$segnale && alarm_displayed=false);");

                if(count($alarm_arr) >= 1)
                {
                    $offset=$alarm_arr[0][2];
                    $id_alarm=$alarm_arr[0][3] + 7; //rientro allarme 13 soglia 14 presoglia
                    $data=strtotime( $DATA_SCHEDULE );
                    $data_sec=$data+ 3600*$offset;
                    $data_less_hour=strftime('%Y-%m-%d %H:%M:%S',$data_sec);


                    $msql->execute($query_alarm." ($segnale,false,$offset,'$data_less_hour',$id_alarm,'$DATA_SCHEDULE');");
                }
            }
        }
   		$msql->disconnettiDB();
        return 0;
    }

    function checkflagSimulazioniAllarm()
    {
	global $DATA_SCHEDULE;

	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();
	
        $msql  = new Db;
        $msql->connect();
        //query vi sono simulazioni flag a 0 e non presenti nella tab allarmi
        $arr=$msql->execute_select("SELECT numero from flag_simulazioni where flag = 0 and numero not in (select num_simulazione FROM alarm_flag_simulazioni where alarm_displayed=true);");
        for($i=0; $i < count($arr);$i++)
        {
           $numero=$arr[$i][0];
           $msql->execute("INSERT INTO alarm_flag_simulazioni (num_simulazione,alarm_displayed,alarm_id,data) VALUES ($numero,true,8,'$DATA_SCHEDULE');");
        }
        //query vi sono simulazioni flag a 1 con allarme inviato precedentemente
        $arr=$msql->execute_select("SELECT numero FROM flag_simulazioni as f join alarm_flag_simulazioni as a ON f.numero=a.num_simulazione && a.alarm_displayed=true && f.flag=1;");
        for($i=0; $i < count($arr);$i++)
        {
           $numero=$arr[$i][0];
           $msql->execute("INSERT INTO alarm_flag_simulazioni (num_simulazione,alarm_displayed,alarm_id,data) VALUES ($numero,false,15,'$DATA_SCHEDULE');");
        }
    }

    function SendTrasmissionAlarm($kind)
    {
        global $DATA_SCHEDULE;

	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();
        
        $msql  = new Db;
        $msql->connect();
        $query_insert="INSERT INTO communications (InsertDate,Destination,kind,Message,alarm_id,id_record,data_alarm) VALUES ";
        $query=$this->makeQuerySearch($kind);
        
        echo $query."\n";
        $arr=$msql->execute_select($query);
        for($row=0;$row<count($arr);$row++)
        {
            $id_record=$arr[$row][0];
            $data=$arr[$row][1];
            $val_trasmissione=$arr[$row][2];
            $val_trasmissione_old=$arr[$row][3];
            $alarm_id=$arr[$row][4];
            $destinatario=$arr[$row][5]; //numero cell; numero fax; email
            $centralina=$arr[$row][6];
            //controllo se gia inviato
            $query="SELECT alrs.* FROM alarm_trasmissione as alrs join communications on alrs.alarm_id=communications.alarm_id && alrs.id=communications.id_record and communications.id_record=$id_record && communications.alarm_id=$alarm_id && kind='$kind';";
            $arr_com=$msql->execute_select($query);
            echo $query."\n";
            if (count($arr_com) == 0) //non ancora inviato
            {
                $txt="Ora [$data] la centralina $centralina ripristinato collegamento completo. Codice di trasmissione 3.";

                if($val_trasmissione == 1)
                   $txt="Ora [$data]  la centralina $centralina trasmette solo diretto. Codice di trasmissione 1.";
                else if ($val_trasmissione == 2)
                   $txt="Ora [$data]  la centralina $centralina trasmette solo da ripetitore. Codice di trasmissione 2.";
                else if ($val_trasmissione == 0)
                    $txt="Ora [$data]  la centralina $centralina non trasmette. Codice di trasmissione 0.";

                $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','$kind','$txt',$alarm_id,$id_record,'$data');");
            }
         }

         $msql->disconnettiDB();
         return 0;
    }

    function SendPresogliaSogliaAlarm($kind)
    {
        global $DATA_SCHEDULE;

	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();

        $msql  = new Db;
        $msql->connect();
        $query_insert="INSERT INTO communications (InsertDate,Destination,kind,Message,alarm_id,id_record,data_alarm) VALUES ";
      //  $query=$this->makeQuerySearch($kind);
        switch($kind)
        {
            case $this->SMS://0
                 //tutti gli allarmi di trasmissione che sono da mandare via sms con i numeri di telefono reperibili
               $query="SELECT alrs.id,alrs.data,alrs.valore,alrs.alarm_id,rs.numero_sms,alrs.Rx,alrs.alarm_displayed FROM alarm_soglia as alrs inner join alarm_table as at on at.send_sms=true && at.alarm_id = alrs.alarm_id inner join rubrica_sms as rs on DATE_FORMAT(alrs.data,'%H:%i:%s') between rs.start_ora and rs.end_ora and DATE_FORMAT(alrs.data,'%w') = rs.day_week order by alrs.data;";
            break;

            case $this->FAX: //1
               $query="SELECT alrs.id,alrs.data,alrs.valore,alrs.alarm_id,rs.numero_fax,alrs.Rx,alrs.alarm_displayed  FROM alarm_soglia as alrs inner join alarm_table as at on at.send_fax=true && at.alarm_id = alrs.alarm_id inner join rubrica_fax as rs order by alrs.data;";
            break;

            case $this->EMAIL: //2
               $query="SELECT alrs.id,alrs.data,alrs.valore,alrs.alarm_id,rs.indirizzo_email,alrs.Rx,alrs.alarm_displayed  FROM alarm_soglia as alrs inner join alarm_table as at on at.send_email=true && at.alarm_id = alrs.alarm_id inner join rubrica_email as rs order by alrs.data;";
            break;
        }
        
        $arr=$msql->execute_select($query);
        echo $query."\n";
        for($row=0;$row<count($arr);$row++)
        {
            $id_record=$arr[$row][0];
            $data=$arr[$row][1];
            $valore=$arr[$row][2];
            $alarm_id=$arr[$row][3];
            $destinatario=$arr[$row][4]; //numero cell; numero fax; email
            $piezo=$arr[$row][5];
            $alarm_displayed=$arr[$row][6];
            if($kind != $this->FAX) //SMS e EMAIL
            {
                //controllo se gia inviato
                $query="SELECT alrs.* FROM alarm_soglia as alrs join communications on alrs.alarm_id=communications.alarm_id && alrs.id=communications.id_record and communications.id_record=$id_record && communications.alarm_id=$alarm_id && kind='$kind';";
                $arr_com=$msql->execute_select($query);
                //echo $query."\n";
                if (count($arr_com) == 0) //non ancora inviato
                {
                    $txt=$this->writeTxtSoglia($alarm_id,$piezo,$data);
                    $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','$kind','$txt',$alarm_id,$id_record,'$data');");
                }
            }
            else
            {
               $query_true="SELECT count(alrs.id) FROM alarm_soglia as alrs join communications on alrs.alarm_id=communications.alarm_id && alrs.id=communications.id_record and communications.kind=\"$this->FAX\" && communications.alarm_id=$alarm_id && alrs.Rx = $piezo && alrs.alarm_displayed=true;";
               $query_false="SELECT count(alrs.id) FROM alarm_soglia as alrs join communications on alrs.alarm_id=communications.alarm_id && alrs.id=communications.id_record and communications.kind=\"$this->FAX\" && communications.alarm_id=$alarm_id && alrs.Rx = $piezo && alrs.alarm_displayed=false;";
               echo $query_true."\n";
               echo $query_false."\n";
               $arr_true=$msql->execute_select($query_true);
               $arr_false=$msql->execute_select($query_false);
               if($arr_true[0][0] == $arr_false[0][0])
               {
                    $txt=$this->writeTxtSoglia($alarm_id,$piezo,$data);
                    $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','$kind','$txt',$alarm_id,$id_record,'$data');");
               }
            }
         }

         $msql->disconnettiDB();
         return 0;
    }

    function SendPresogliaSogliaPrevAlarm($kind)
    {
        global $DATA_SCHEDULE;
	
	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();
        
	$msql  = new Db;
        $msql->connect();
        $query_insert="INSERT INTO communications (InsertDate,Destination,kind,Message,alarm_id,id_record,data_alarm) VALUES ";
//        $query=$this->makeQuerySearch($kind);
        switch($kind)
        {
            case $this->SMS://0
                 //tutti gli allarmi di trasmissione che sono da mandare via sms con i numeri di telefono reperibili
                 $query="SELECT alrs.id,alrs.offset,alrs.alarm_id,rs.numero_sms,alrs.Rx,alrs.data_previsione,alrs.data FROM alarm_preallarme_previsione as alrs inner join alarm_table as at on at.send_sms=true && at.alarm_id = alrs.alarm_id inner join rubrica_sms as rs on DATE_FORMAT(alrs.data,'%H:%i:%s') between rs.start_ora and rs.end_ora and DATE_FORMAT(alrs.data,'%w') = rs.day_week order by alrs.data;";
            break;
            case $this->FAX: //1
                $query="SELECT alrs.id,alrs.offset,alrs.alarm_id,rs.numero_fax,alrs.Rx,alrs.data_previsione,alrs.data FROM alarm_preallarme_previsione as alrs inner join alarm_table as at on at.send_fax=true && at.alarm_id = alrs.alarm_id inner join rubrica_fax as rs order by alrs.data;";
            break;
            case $this->EMAIL: //2
               $query="SELECT alrs.id,alrs.offset,alrs.alarm_id,rs.indirizzo_email,alrs.Rx,alrs.data_previsione,alrs.data FROM alarm_preallarme_previsione as alrs inner join alarm_table as at on at.send_email=true && at.alarm_id = alrs.alarm_id inner join rubrica_email as rs order by alrs.data;";
            break;
        }

        echo $query."\n";
        $arr=$msql->execute_select($query);
        for($row=0;$row<count($arr);$row++)
        {
            $id_record=$arr[$row][0];
            $offset=$arr[$row][1];
            $alarm_id=$arr[$row][2];
            $destinatario=$arr[$row][3]; //numero cell; numero fax; email
            $centralina=$arr[$row][4];
            $data_previsione=$arr[$row][5];
            $data=$arr[$row][6];
            //controllo se gia inviato
            $query="SELECT alrs.* FROM alarm_preallarme_previsione as alrs join communications on alrs.alarm_id=communications.alarm_id && alrs.id=communications.id_record and communications.id_record=$id_record && communications.alarm_id=$alarm_id && kind='$kind';";
            $arr_com=$msql->execute_select($query);
            echo $query."\n";
            if (count($arr_com) == 0) //non ancora inviato
            {
    
                if($alarm_id == 6)
                    $txt="Ora [$data] Previsione nella sezione $centralina soglia di preallarme superata tra $offset ore ($data_previsione)";
                else if($alarm_id == 13)
                    $txt="Ora [$data] Rientrato Previsione preallarme soglia nel piezometro $piezo";
                else if($alarm_id == 7)
                    $txt="Ora [$data] Previsione nella sezione $centralina soglia di allarme superata tra $offset ore ($data_previsione)";
                else if($alarm_id == 14)
                    $txt="Ora [$data] Rientrato Previsione allarme soglia nel piezometro $piezo";

                $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','$kind','$txt',$alarm_id,$id_record,'$data');");
            }
         }

         $msql->disconnettiDB();
         return 0;
    }


    function SendModelliPrevisioni($kind)
    {
        global $DATA_SCHEDULE;

	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();
	
        $msql  = new Db;
        $msql->connect();
        $query_insert="INSERT INTO communications (InsertDate,Destination,kind,Message,alarm_id,id_record,data_alarm) VALUES ";

        switch($kind)
        {
            case $this->SMS://0
                 //tutti gli allarmi di trasmissione che sono da mandare via sms con i numeri di telefono reperibili
                $query="SELECT alrs.id,alrs.num_simulazione,alrs.alarm_id,rs.numero_sms,alrs.data FROM alarm_flag_simulazioni as alrs inner join alarm_table as at on at.send_sms=true && at.alarm_id = alrs.alarm_id inner join rubrica_sms as rs on DATE_FORMAT(alrs.data,'%H:%i:%s') between rs.start_ora and rs.end_ora and DATE_FORMAT(alrs.data,'%w') = rs.day_week order by alrs.data;";
            break;
            case $this->FAX: //1
                $query="SELECT alrs.id,alrs.num_simulazione,alrs.alarm_id,rs.numero_fax,alrs.data FROM alarm_flag_simulazioni as alrs inner join alarm_table as at on at.send_fax=true && at.alarm_id = alrs.alarm_id inner join rubrica_fax as rs order by alrs.data;";
            break;
            case $this->EMAIL: //2
               $query="SELECT alrs.id,alrs.num_simulazione,alrs.alarm_id,rs.indirizzo_email,alrs.data FROM alarm_flag_simulazioni as alrs inner join alarm_table as at on at.send_email=true && at.alarm_id = alrs.alarm_id inner join rubrica_email as rs order by alrs.data;";
            break;
        }

        echo $query."\n";
        $arr=$msql->execute_select($query);
        for($row=0;$row<count($arr);$row++)
        {
            $id_record=$arr[$row][0];
            $num_simulazione=$arr[$row][1];
            $alarm_id=$arr[$row][2];
            $destinatario=$arr[$row][3]; //numero cell; numero fax; email
            $data=$arr[$row][4];
            //controllo se gia inviato
            $query="SELECT alrs.* FROM alarm_flag_simulazioni as alrs join communications on alrs.alarm_id=communications.alarm_id && alrs.id=communications.id_record and communications.id_record=$id_record && communications.alarm_id=$alarm_id && kind='$kind';";
            $arr_com=$msql->execute_select($query);
            echo $query."\n";
            if (count($arr_com) == 0) //non ancora inviato
            {

                if($alarm_id == 8)
                    $txt="Ora [$data] Simulazione sezione $num_simulazione non completata";
                else if($alarm_id == 15)
                    $txt="Ora [$data] Simulazione sezione $num_simulazione ripristinata";

                $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','$kind','$txt',$alarm_id,$id_record,'$data');");
            }
         }

         $msql->disconnettiDB();
         return 0;
    }
    
    function getDay($data_inp)
    {
      $DAY_OF_WEEK = array("Dom","Lun","Mar","Mer","Gio","Ven","Sab");
      $data=strtotime( $data_inp );
      $day=strftime('%w',$data);
      return $DAY_OF_WEEK[$day];
    }

    function writeTxtSoglia($alarm_id,$piezo,$data)
    {
        if($alarm_id == 4)
            $txt="Ora [$data] Soglia di Preallarme superata nel piezometro $piezo ";
        else if($alarm_id == 11)
            $txt="Ora [$data] Rientrato Preallarme soglia nel piezometro $piezo ";
        else if($alarm_id == 5)
            $txt="Ora [$data] Soglia di Allarme superata nel piezometro $piezo ";
        else if($alarm_id == 12)
            $txt="Ora [$data] Rientrato Allarme soglia nel piezometro $piezo ";
        return $txt;
    }
    
    function makeQuerySearch($kind)
    {
        switch($kind)
        {
            case $this->SMS://0
                 //tutti gli allarmi di trasmissione che sono da mandare via sms con i numeri di telefono reperibili
                 $query="SELECT alrs.id,alrs.data,alrs.val_trasmissione,alrs.val_trasmissione_old,alrs.alarm_id,rs.numero_sms,alrs.Rx FROM alarm_trasmissione as alrs inner join alarm_table as at on at.send_sms=true && at.alarm_id = alrs.alarm_id inner join rubrica_sms as rs on DATE_FORMAT(alrs.data,'%H:%i:%s') between rs.start_ora and rs.end_ora and DATE_FORMAT(alrs.data,'%w') = rs.day_week order by alrs.data;";
            break;

            case $this->FAX: //1
                $query="SELECT alrs.id,alrs.data,alrs.val_trasmissione,alrs.val_trasmissione_old,alrs.alarm_id,rs.numero_fax,alrs.Rx FROM alarm_trasmissione as alrs inner join alarm_table as at on at.send_fax=true && at.alarm_id = alrs.alarm_id inner join rubrica_fax as rs order by alrs.data;";
            break;

            case $this->EMAIL: //2
               $query="SELECT alrs.id,alrs.data,alrs.val_trasmissione,alrs.val_trasmissione_old,alrs.alarm_id,rs.indirizzo_email,alrs.Rx FROM alarm_trasmissione as alrs inner join alarm_table as at on at.send_email=true && at.alarm_id = alrs.alarm_id inner join rubrica_email as rs order by alrs.data;";
            break;
        }
        return $query;
    }
    
    function SendStatusSistem($kind)
    {
        $DATA_SCHEDULE=strftime('%Y-%m-%d %H:%M:%S',time());

	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();
        
        $msql  = new Db;
        $msql->connect();
        $query_insert="INSERT INTO communications (InsertDate,Destination,kind,Message,alarm_id,id_record,data_alarm) VALUES ";
        
        switch($kind)
        {
            case $this->SMS://0
                 //tutti gli allarmi di trasmissione che sono da mandare via sms con i numeri di telefono reperibili
               $query="SELECT rs.numero_sms FROM alarm_table AS at INNER JOIN rubrica_sms AS rs ON at.send_sms = true && at.alarm_id =1 && rs.id_allarm =1 && DATE_FORMAT( now( ) , '%w' ) = rs.day_week and DATE_FORMAT( now(),'%H:%i:%s') between rs.start_ora and rs.end_ora;";
            break;

            case $this->FAX: //1
               $query="SELECT rs.numero_fax FROM alarm_table AS at INNER JOIN rubrica_fax AS rs ON at.send_fax = true && at.alarm_id =1 && rs.id_allarm =1;";
            break;

            case $this->EMAIL: //2
               $query="SELECT rs.indirizzo_email FROM alarm_table AS at INNER JOIN rubrica_email AS rs ON at.send_email = true && at.alarm_id =1 && rs.id_allarm =1;";
            break;
        }
        
        echo $query."\n";
        $arr=$msql->execute_select($query);
        $text=$msql->execute_select("SELECT text FROM alarm_status ORDER BY data DESC LIMIT 1;");
        $TEXT_STATUS_MSG=$text[0][0];

        for($row=0;$row<count($arr);$row++)
        {          
            $destinatario=$arr[$row][0]; //numero cell; numero fax; email
            //controllo se gia inviato
            
            if($TEXT_STATUS_MSG=='')
                $txt="Ora [$DATA_SCHEDULE] Sistema di previsione in tempo reale argini Fiumi Uniti funzionante";
            else
                $txt="Ora [$DATA_SCHEDULE] Sistema di previsione in tempo reale argini Fiumi Uniti funzionante con errori:
                $TEXT_STATUS_MSG";
            $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','$kind','$txt',1,1,'$DATA_SCHEDULE');");
           
            $msql->execute("DELETE FROM alarm_status;");

         }
         
         $msql->disconnettiDB();
         return 0;
    }

    function getIPs($withV6 = true)
    {
        preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', `ifconfig`, $ips);
        return $ips[1];
    }

    function SendArchivioSistem($archivio,$start_data,$end_data,$checksum,$stringa)
    {
        $DATA_SCHEDULE=strftime('%Y-%m-%d %H:%M:%S',time());

	$log=new FileLog();
	$log->writeLog(__FUNCTION__);
	$log->close();
        
        $msql  = new Db;
        $msql->connect();
        $query_insert="INSERT INTO communications (InsertDate,Destination,kind,Message,alarm_id,id_record,data_alarm,path_archivio) VALUES ";
        
        $query="SELECT rs.indirizzo_email FROM alarm_table AS at INNER JOIN rubrica_email AS rs ON at.send_email = true && at.alarm_id =1 && rs.id_allarm =1;";
        
        echo $query."\n";
        $arr=$msql->execute_select($query);
        
        
        $ips = $this->getIPs();
        print_r($ips);
        for($row=0;$row<count($arr);$row++)
        {          
            $destinatario=$arr[$row][0]; // email
            
            $txt="Ora [$DATA_SCHEDULE] Sistema di previsione in tempo reale argini Fiumi Uniti: Archivio@
                  Bisogna eliminare i dati di $stringa periodo: $start_data al $end_data@
                  Elimina http://$ips[0]/EliminaDati.php?check=$checksum";
            
            $msql->execute($query_insert."('$DATA_SCHEDULE','$destinatario','email','$txt',1,1,'$DATA_SCHEDULE','$archivio');");
            
         }

         $msql->disconnettiDB();
         return 0;
    }
}
?>
